/*
 * lib2Desa - Another 2D game library in C++
 * Copyright (C) 2009 Erivaldo Xavier de Lima Filho
 *
 * This program is free software and is distributed under GNU General Public License version 3. You can modify and/or redistribute
 * it under the terms of GPL version 3 or posterior version. This program comes with NO WARRANTY, for more details, see LICENSE,
 * or <http://www.gnu.org/licenses>.
 *
 * Contact info:
 *
 *	Erivaldo Xavier de Lima Filho, desadoc@gmail.com
 *
 */

#include "Core/Scene.hpp"

#ifndef _NO_NAMESPACE
namespace lib2Desa {
#endif

void Scene::runGroups(u32 ml)
{
	std::list<shared_ptr<GameObjectGroup> >::iterator it = groups.begin();

	for(; it != groups.end(); it++)
	{
		(*it)->run(ml);
	}
}

void Scene::runRules(void)
{
	std::list<shared_ptr<IGameRule> >::iterator it = rules.begin();

	for(; it != rules.end(); it++)
	{
		(*it)->processEvents();
		(*it)->notifyListeners();
	}
}

Scene::Scene(void)
{
	background = null;
}

Scene::~Scene(void)
{
	if(background)
		background = null;

	std::list<shared_ptr<GameObjectGroup> >::iterator it = groups.begin();

	for(; it != groups.end(); it++)
	{
		(*it) = null;
	}
}

void Scene::draw(const shared_ptr<IGraphicDevice>& gd) const
{
	if(background) gd->drawSprite(background);

	std::list<shared_ptr<GameObjectGroup> >::const_iterator it = groups.begin();

	for(; it != groups.end(); it++)
	{
		(*it)->draw(gd);
	}
}

bool Scene::run(u32 ml)
{
	runGroups(ml);
	runRules();

	return true;
}

void Scene::addGroup(const shared_ptr<GameObjectGroup>& g)
{
	groups.push_back(g);
}

bool Scene::removeGroup(const shared_ptr<GameObjectGroup>& g)
{
	std::list<shared_ptr<GameObjectGroup> >::iterator it = groups.begin();

	for(; it != groups.end(); it++)
	{
		if(g == (*it))
		{
			groups.erase(it);
			return true;
		}
	}

	return false;
}

void Scene::addRule(shared_ptr<IGameRule> r)
{
	r->setTargetGroups(&groups);
	rules.push_back(r);
}

bool Scene::removeRule(const shared_ptr<IGameRule>& r)
{
	std::list<shared_ptr<IGameRule> >::iterator it = rules.begin();

	for(; it != rules.end(); it++)
	{
		if(r == (*it))
		{
			rules.erase(it);
			return true;
		}
	}

	return false;
}

#ifndef _NO_NAMESPACE
}
#endif
